package com.order.service.impl;

import com.order.context.BaseContext;
import com.order.entity.ShoppingCart;
import com.order.exception.ProductNotFoundException;
import com.order.mapper.CartMapper;
import com.order.mapper.ProductMapper;
import com.order.service.CartService;
import com.order.service.ProductService;
import com.order.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<ShoppingCart> search(Long userId) {
        return cartMapper.getByUserId(userId);
    }

    @Override
    public void add(ShoppingCart shoppingCart) {


            ProductVo product = productMapper.getById(shoppingCart.getProductId());
            if(product == null){
                throw new ProductNotFoundException("商品不存在");
            }

            ShoppingCart cart = cartMapper.selectByUserIdAndProductId(BaseContext.getCurrentId(), product.getId());
            if(cart == null){
                shoppingCart.setName(product.getName());
                shoppingCart.setImage(product.getImage());
                shoppingCart.setUserId(BaseContext.getCurrentId());

                cartMapper.insert(shoppingCart);
            }else {
                cart.setQuantity(cart.getQuantity() + 1);
                cart.setAmount(product.getCurrentPrice().add(cart.getAmount()));
                cartMapper.update(cart);
            }





    }

    @Override
    public void update(ShoppingCart shoppingCart) {
        cartMapper.update(shoppingCart);
    }

    @Override
    public void delete(List<Long> ids) {
        cartMapper.deleteByIds(ids);
    }

    @Override
    public void deleteAll() {
        cartMapper.deleteByUserId(BaseContext.getCurrentId());
    }


}
